<template>
  <div class="form-container">
    <!-- 简化的操作栏 -->
    <div class="action-bar">
      <el-input v-model="keyword" placeholder="搜索表单名称" clearable @keyup.enter.native="onSearch" @clear="onSearch" style="width: 240px; margin-right: 8px;" />
      <el-button 
        type="primary" 
        @click="handleCreate" 
        size="default"
      >
        创建表单
      </el-button>
    </div>
    
    
    <!-- 表单表格 -->
    <div class="table-wrapper">
      <el-table 
        :data="forms" 
        style="width: 100%" 
        v-loading="loading"
        element-loading-text="加载表单列表..."
        :height="'calc(100vh - 290px)'"
        stripe
      >
        <el-table-column prop="name" label="表单名称" min-width="120" show-overflow-tooltip />
        <el-table-column label="表单OID" min-width="220" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="text-muted">{{ row._id || row.id }}</span>
          </template>
        </el-table-column>
        <!-- 合并：布局列【方向|分页】，例如【纵向|连续】、【横向|连续】、【横向|单页】 -->
        <el-table-column label="布局" width="120" align="center">
          <template #default="{ row }">
            <el-tooltip :content="getLayoutTip(row)" placement="top" trigger="click">
              <span>{{ getLayoutText(row) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="order" label="排序" width="80" align="center" />
        <el-table-column label="创建时间" width="160">
          <template #default="{ row }">
            <span class="text-muted">{{ formatDate(row.createTime || row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button link type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button link type="primary" size="small" @click="handleFieldConfig(row)" :loading="configSaving" :disabled="configSaving">配置字段</el-button>
              <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination 
          v-if="pagination" 
          :current-page="pagination.page"
          :page-size="pagination.limit" 
          :total="pagination.total" 
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange" 
          @current-change="handlePageChange"
          small
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import FormBasicInfo from '@/components/form/FormBasicInfo.vue'
import FormPreview from '@/components/FormPreview.vue'
import { addDialog } from '@/components/gDialog'
import { useFormStore } from '@/stores/form'

const router = useRouter()
const route = useRoute()
const formStore = useFormStore()
const forms = ref([])
const loading = ref(false)
const configSaving = ref(false)
const pagination = ref(null)
const keyword = ref('')

const queryParams = reactive({
  page: 1,
  limit: 10,
  sortBy: 'order',
  sortOrder: 'asc',
  projectId: null
});


// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取表单列表
const getForms = async () => {
  loading.value = true
  try {
    const response = await formStore.getAllForms({ ...queryParams, name: keyword.value?.trim() })
    forms.value = response.data
    pagination.value = response.pagination
  } catch (error) {
    ElMessage.error('获取表单列表失败')
  } finally {
    loading.value = false
  }
}

const onSearch = () => {
  queryParams.page = 1
  getForms()
}

onMounted(() => {
  const projectId = route.params.projectId;
  if (projectId) {
    queryParams.projectId = projectId;
    getForms();
  }
});

const handleSizeChange = (size) => {
  queryParams.limit = size;
  getForms();
};

const handlePageChange = (page) => {
  queryParams.page = page;
  getForms();
};


// 创建表单
const handleCreate = () => {
  // 计算下一个排序号：使用表单总数 + 1
  const nextOrder = (pagination.value?.total || 0) + 1

  addDialog({
    title: '创建表单',
    width: '500px',
    component: FormBasicInfo,
    props: {
      editData: {
        order: nextOrder,  // 自动设置排序号
        projectId: queryParams.projectId
      }
    },
    callBack: async (data) => {
      if (data) {
        try {
          const newForm = await formStore.createForm(data)
          ElMessage.success('创建成功')
          // 刷新表单列表，确保下次创建时排序号正确
          await getForms()
          // 创建成功后直接跳转到表单配置页面
          const formId = newForm.id || newForm._id
          if (formId) {
            router.push({
              name: 'FormConfig',
              params: {
                formId: formId
              },
              query: {
                formId: formId,
                name:data.name
              }
            })
          }
        } catch (error) {
          ElMessage.error('创建失败')
        }
      }
    }
  })
}

// 编辑表单
const handleEdit = (row) => {
  addDialog({
    title: '编辑表单',
    width: '500px',
    component: FormBasicInfo,
    props: {
      editData: row
    },
    callBack: async (data) => {
      if (data) {
        try {
          await formStore.updateForm({ ...data, id: row._id })
          ElMessage.success('更新成功')
          getForms()
        } catch (error) {
          ElMessage.error('更新失败')
        }
      }
    }
  })
}

// 配置字段 - 通过路由跳转
const handleFieldConfig = (row) => {
  const formId = row.id || row._id
  if (!formId) {
    ElMessage.error('表单ID无效')
    return
  }

  // 跳转到表单配置页面
  // router.push({
  //   name: 'FormConfig',
  //   params: {
  //     formId: formId,
  //     name:row.name
  //   },
  //   query: {
  //     name:row.name
  //   }
  // })
  // router.push通过 path 跳转
  router.push({
    path: `/forms/${formId}/config`,
    params: {
      formId: formId
    },
    query: {
      formId: formId,
      name:row.name
    }
  })
}

// 预览表单
const handlePreview = (row) => {
  // 检查表单是否有配置
  if (!row.config || !row.config.fields || row.config.fields.length === 0) {
    ElMessage.warning('该表单还没有配置字段，请先配置后再预览')
    return
  }

  // 打开预览对话框
  addDialog({
    title: `预览表单 - ${row.name}`,
    width: '80%',
    component: FormPreview,
    props: {
      formData: row,
      fields: row.config.fields
    }
  })
}

// 删除表单
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该表单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await formStore.deleteForm(row._id)
      ElMessage.success('删除成功')
      getForms()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}



// 初始化
// getForms() // This line is now handled by onMounted

// 暴露方法给父组件调用
defineExpose({
  getForms,
  queryParams
})

// 布局展示文案
const getLayoutText = (row) => {
  const orientation = row?.config?.formConfig?.pageOrientation === 'landscape' ? '横向' : '纵向'
  const isolation = row?.config?.formConfig?.pageIsolation === true ? '单页' : '连续'
  return `${orientation}|${isolation}`
}

// 布局提示说明
const getLayoutTip = (row) => {
  const isLandscape = row?.config?.formConfig?.pageOrientation === 'landscape'
  const isSinglePage = row?.config?.formConfig?.pageIsolation === true
  const o = isLandscape ? '横向纸张：仅本表单横向' : '纵向纸张：默认方向'
  const p = isSinglePage ? '单页：表单内容单独一页' : '连续：与相邻内容连续排版'
  return `${o}\n${p}\n(点击可再次查看说明)`
}
</script>

<style scoped>
/* 取消徽标样式，使用普通文本展示 */
.form-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

/* 操作栏样式 */
.action-bar {
  position: absolute;
    right: 0;
    top: -32px;
    z-index: 0;
}

/* 表格容器 */
.table-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  margin-top: 10px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

:deep(.el-table__header) {
  background: #fafafa;
}

:deep(.el-table th) {
  background: #fafafa !important;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #e4e7ed;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 0;
}

:deep(.el-table__row:hover) {
  background: #f8f9fa;
}

/* 操作按钮组 */
.action-buttons {
  display: flex;
  gap: 4px;
  align-items: center;
}

.action-buttons .el-button + .el-button {
  margin-left: 0;
}

/* 文本样式 */
.text-muted {
  color: #909399;
  font-size: 13px;
}

/* 分页容器 */
.pagination-wrapper {
  padding: 16px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-bar {
    padding: 12px 0;
  }
  
  .table-wrapper {
    margin: 0 -8px;
  }
  
  :deep(.el-table) {
    border-radius: 0;
  }
  
  .pagination-wrapper {
    padding: 12px 8px;
  }
}

/* 美化滚动条 */
:deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>